package cn.netty.example4;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 *
 * <p>Title: EchoServer</p>
 * <p>Description:使用FixedLengthFrameDecoder解码器</p>
 * @version V1.0
 * @author ZhiPeng_Chen
 * @date: 2018/10/31
 */
public class EchoServer {

    private NioEventLoopGroup acceptorGroup;
    private NioEventLoopGroup workGroup;
    private ServerBootstrap  serverBootstrap;


    private void init(){
        this.acceptorGroup = new NioEventLoopGroup();
        this.workGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.group(acceptorGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024)
                .handler(new LoggingHandler(LogLevel.INFO));
    }

    public EchoServer(){
        init();
    }

    /**
     * FixedLengthFrameDecoder解码器 无论一次接收多少的数据
     * 都会按照构造函数中的字符数量进行解码 如果数量不够会等下个包达到数量后进行读取
     * 通常用于和客户端约定数量(生产环境不适用)
     * @param port
     * @return
     * @throws InterruptedException
     */
    public ChannelFuture doAcceptor(int port) throws InterruptedException {
        this.serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new FixedLengthFrameDecoder(10));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new EchoServerHandler());
            }
        });

        ChannelFuture future = this.serverBootstrap.bind(port).sync();

        return future;
    }

    public void release(){
        this.workGroup.shutdownGracefully();
        this.acceptorGroup.shutdownGracefully();
    }


    public static void main(String[] args) {
        EchoServer server = new EchoServer();
        ChannelFuture future = null;

        try {
            future = server.doAcceptor(8888);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }finally {
            server.release();
        }
    }

}
